import React from 'react';
import { Button } from 'antd';
import ReactDOM from 'react-dom';
const { unstable_batchedUpdates } = ReactDOM;

interface IProps {}

interface IState {
  number: number;
}

class Counter extends React.Component<IProps, IState> {
  // this.state
  state = {
    number: 0,
  };

  handleClick = () => {
    // this问题
    this.setState({ ...this.state, number: this.state.number + 10 }, () => {
      console.log(this.state.number);
    });
  };

  // 在react17和react18中的表现是不一样的
  handleSync = () => {
    this.setState({ number: this.state.number + 1 });
    console.log(this.state.number); // 0
    this.setState({ number: this.state.number + 1 });
    console.log(this.state.number); // 0
    this.setState({ number: this.state.number + 1 });
    console.log(this.state.number); // 0

    setTimeout(() => {
      this.setState({ number: this.state.number + 1 });
      console.log(this.state.number); // 2
      this.setState({ number: this.state.number + 1 });
      console.log(this.state.number); // 3
      this.setState({ number: this.state.number + 1 });
      console.log(this.state.number); // 4
    });

    setTimeout(() => {
      // unstable_batchedUpdates(() => {
      this.setState({ number: this.state.number + 1 });
      console.log(this.state.number); // 4
      this.setState({ number: this.state.number + 1 });
      console.log(this.state.number); // 4
      this.setState({ number: this.state.number + 1 });
      console.log(this.state.number); // 4
      // });
    }, 1000);
  };

  render() {
    return (
      <div>
        <Button onClick={this.handleClick}>+</Button>
        <p>类组件: {this.state.number}</p>
        <Button onClick={this.handleSync}>sync</Button>
      </div>
    );
  }
}

export default Counter;
